// ignore_for_file: unused_import, library_private_types_in_public_api, depend_on_referenced_packages, empty_catches

import 'dart:io';

import 'package:customer_log_app/global/global.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:customer_log_app/global/log_helper.dart';
import 'package:customer_log_app/global/console.dart';
import 'package:screen_retriever/screen_retriever.dart';
import 'package:window_manager/window_manager.dart';
import 'global/lang_provider.dart';
import 'main_view.dart';
import 'view/home/home.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
import 'package:rxdart/subjects.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

import 'dart:async';
import 'dart:convert';

import 'dart:typed_data';

import 'package:device_info/device_info.dart';
import 'package:image/image.dart' as image;
import 'package:path_provider/path_provider.dart';

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

final BehaviorSubject<ReceivedNotification> didReceiveLocalNotificationSubject =
    BehaviorSubject<ReceivedNotification>();

final BehaviorSubject<String?> selectNotificationSubject =
    BehaviorSubject<String?>();

class ReceivedNotification {
  ReceivedNotification({
    required this.id,
    required this.title,
    required this.body,
    required this.payload,
  });

  final int id;
  final String? title;
  final String? body;
  final String? payload;
}

String? selectedNotificationPayload;

main() async {
  initNotification();
  try {
    Global.loadTransFile();
  } catch (e) {}
  try {
    Global.loadHomePageMenus();
  } catch (e) {}
  try {
    WidgetsFlutterBinding.ensureInitialized();
  } catch (e) {
    log(e);
  }
  try {
    await windowManager.ensureInitialized();
  } catch (e) {
    log(e);
  }

  try {
    var b = Platform.isWindows || Platform.isLinux || Platform.isMacOS;
    if (b) {
      WindowOptions windowOptions = const WindowOptions(
        // size: Size(500, 900),
        center: true,
        backgroundColor: Colors.transparent,
        skipTaskbar: false,

        // titleBarStyle: TitleBarStyle.normal,
      );
      windowManager.waitUntilReadyToShow(windowOptions, () async {
        try {
          var primaryDisplay = await screenRetriever.getPrimaryDisplay();
          var width = primaryDisplay.size.width;
          var height = primaryDisplay.size.height;
          log('size: width=$width,height:$height');
          await windowManager.show();
          await windowManager.focus();
          await windowManager.setMaximizable(false);
          await windowManager.setResizable(true);
          log('set windwo size');
          var appHeight = height * 0.8;
          var appWidth = appHeight * 0.5;
          Global.appHeight = appHeight;
          Global.appWidth = appWidth;
          await windowManager.setSize(Size(appWidth, appHeight), animate: true);
          await windowManager.setMaximizable(false);
          await windowManager.center(animate: true);
        } catch (e) {
          log('windowManager error');
          log(e);
        }
      });
    }
  } catch (e1) {
    log('pc error');
    log(e1);
  }

  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (context) => LangProvider()),
    ],
    child: const MyApp(),
  ));
  // runApp(const MyApp());
}

void initNotification() async {
  try {
    try {
      WidgetsFlutterBinding.ensureInitialized();
    } catch (e1) {
      log('WidgetsFlutterBinding error');
      log(e1);
    }

    await _configureLocalTimeZone();
  } catch (e) {
    log('init Notification error');
    log(e);
  }
}

Future<void> _configureLocalTimeZone() async {
  try {
    if (kIsWeb || Platform.isLinux) {
      return;
    }
    tz.initializeTimeZones();
    tz.setLocalLocation(tz.getLocation('Asia/Shanghai'));
  } catch (e) {
    log('tomezone error');
    log(e);
  }
}

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WindowListener {
  @override
  void initState() {
    try {
      windowManager.addListener(this);
    } catch (e) {
      log('windowManger error');
      log(e);
    }
    super.initState();
  }

  @override
  void dispose() {
    try {
      windowManager.removeListener(this);
    } catch (e) {
      log('windowManger error');
      log(e);
    }
    super.dispose();
  }

  @override
  void onWindowResize() {
    log('resize');
    try {
      build(context);
    } catch (e) {
      log('resize error');
      log(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    var phoneSize = MediaQuery.of(context).size;
    Global.appHeight = phoneSize.height;
    Global.appWidth = phoneSize.width;
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primaryColor: Colors.black),
      // themeMode: _themeMode,
      navigatorKey: navigatorKey,

      routes: {
        "/": (context) => const Main(),
      },
      initialRoute: getInitialRoute(),
    );
  }

  getInitialRoute() {
    return '/';
  }
}
